package Behaviour;

import jade.core.behaviours.OneShotBehaviour;

import java.awt.Point;
import java.util.Random;

import map.Map;
import Model.Car;
import View.PanelGui;

public class AddCar extends OneShotBehaviour {

	private static final long serialVersionUID = -6016081137124245471L;
	private Map map;
	private PanelGui panelGui;
	private int STEP;

	public AddCar(Map map, PanelGui panel, int i) {
		super();
		this.map = map;
		this.STEP = i;
		this.panelGui = panel;
	}

	@Override
	public void action() {
		Integer customSteps = (Integer) panelGui.stepcombo.getSelectedItem();
		Integer customCars = (Integer) panelGui.carcombo.getSelectedItem();
		if (customSteps > 0) {
			if (STEP % customSteps == 0) {
				for (int i = 0; i < customCars; ++i) {
					Random generator = new Random();
					int inOut = generator.nextInt(2);
					int entry = generator.nextInt(this.map.getEntries().size() - 1);
					int exit = 0;
					Point start = new Point(this.map.getEntries().get(entry).getCoordEntry());
					Point arrive = null;
					if (inOut % 2 == 0) {
						exit = (entry * 2 + 1)% (this.map.getEntries().size());
						arrive = new Point(this.map.getEntries().get(exit).getCoordExit());
					} else {
						
						exit = new Random().nextInt(map.getRandomPos().size());
						arrive = new Point(map.getRandomPos().get(exit));
						while(!map.getNextNearestCrossRoads(start).equals(map.getPrecNearestCrossRoads(arrive))){
							exit = new Random().nextInt(map.getRandomPos().size());
							arrive = new Point(map.getRandomPos().get(exit));
						}
					}
//					System.out.println("ADD IN LIST " + start + arrive);
					Car c = new Car(start, arrive, map);
//					System.out.println("@@@");
					// CONTROLLO CHE L'AUTO GENERATA POSSA ENTRARE,
					// ALTRIMENTI VA IN WAIT
					// if (this.map.getMap()[start.x][start.y].isOccupied()
					// || this.map.getFirstCarFromWaitList(start) != null) {
					this.map.addCarToWaitLists(c, start);
					// } else {
					// this.map.addCar(c);
					// this.map.getMap()[start.x][start.y].setOccupied(true);
					// }
				}
			}
		}

	}

}
